package com.lecture.java8.datastructure;

/**
 * @author luyn
 * @version 1.0
 * @description
 * @date 2021/3/24 10:25
 */
public class Demo4Discuss3 {
    public static void main(String[] args) {
        long starttime,endtime;     //统计运行耗时
        int times = 1000000;     //重复计算次数

        double[] a = new double[101];   //定义多项式系数
        a[0] = 1;
        //循环添加多项式系数
        for (int i = 1; i <= 100; i++) {
            a[i] = 1.0 / i;
        }

        double num1 = 0;    //存储计算方法一得出的结果
        double num2 = 0;    //存储计算方法二得出的结果

        starttime = System.nanoTime();
        for (int i = 0; i < times; i++){
            num1 = funcA(a.length-1, a, 1.1);
        }
        endtime = System.nanoTime();
        System.out.println("num1耗时：" + (endtime - starttime) + "ns");

        starttime = System.nanoTime();
        for (int i = 0; i < times; i++){
            num2 = funcB(a.length-1, a, 1.1);
        }
        endtime = System.nanoTime();
        System.out.println("num2耗时：" + (endtime - starttime) + "ns");

        System.out.println(num1);
        System.out.println(num2);
    }

    //计算方式一
    public static double funcA(int n, double[] a, double x){
        double p = a[0];
        for (int i = 1; i <= n; i++){
            p += (a[i] * Math.pow(x, i));
        }
        return p;
    }

    //计算方式二
    public static double funcB(int n, double[] a, double x){
        double p = a[n];
        for (int i = n; i > 0; i--){
            p = a[i-1] + x * p;
        }
        return p;
    }
}
